{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# §2: Basic Python\n",
    "\n",
    "\n",
    "### content\n",
    "## 2.1 basic\n",
    "## 2.2 data structure\n",
    "## 2.3 cyclic\n",
    "## 2.4 function\n",
    "## 2.5 string\n",
    "## 2.6 file\n",
    "## 2.7 list comprehension\n",
    "## 2.8 module\n",
    "## 2.9 exception\n",
    "## 2.10 Object-Oriented Programming"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.1 basic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello world\n",
      "Who\n",
      "am\n",
      "I\n"
     ]
    }
   ],
   "source": [
    "print('hello world') # row comment start after #\n",
    "a = \"Wang's pen\" #both ' and \"\n",
    "\n",
    "#triple-quoted strings begin and end with three double quotes or three single quotes.\n",
    "#It can create multiline strings or use as comment of multilines\n",
    "b = '''Who\n",
    "am\n",
    "I'''\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### number\n",
    "\n",
    "A number starts with 0b indicate binary\n",
    "\n",
    "starts with 0x is hexadecimal\n",
    "\n",
    "starts with 0o is octonary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3 9 16 3.0 1 0.10000000000000009\n"
     ]
    }
   ],
   "source": [
    "print(1+0b10, 0xa-1, 0o10*2, 7.0//2.0, 3%2, 1.1%0.5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### data type"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'int'>\n",
      "<class 'float'>\n",
      "<class 'bool'>\n",
      "<class 'complex'>\n",
      "<class 'str'>\n",
      "a 97 0b1010 0xa 0o12\n",
      "2.0\n"
     ]
    }
   ],
   "source": [
    "print(type(2))\n",
    "print(type(3.5))\n",
    "print(type(True))\n",
    "print(type(1+2j))\n",
    "print(type('hello'))\n",
    "print(chr(97), ord('a'), bin(10), hex(10), oct(10))\n",
    "c = 2\n",
    "print(float(c))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### operator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "2.6666666666666665\n",
      "2\n",
      "8\n",
      "6\n"
     ]
    }
   ],
   "source": [
    "print(8%3) #remainder operator\n",
    "print(8/3)\n",
    "print(8//3) #floor division operator\n",
    "print(2**3) #exponentiation operator\n",
    "\n",
    "a = 5 #asignment symbol, do not confusing with equality!\n",
    "a += 1\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### variable\n",
    "\n",
    "A variable name should consist of letters, digits and underscores(_), but may not begin with a digit. Unicode is also allowed.The name is case sensitive."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "170\n"
     ]
    }
   ],
   "source": [
    "math_score = 80\n",
    "computer_score = 90\n",
    "print(math_score+computer_score)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " A name cannot be same with python reserved words.\n",
    " \n",
    " The total reserved words are:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']\n"
     ]
    }
   ],
   "source": [
    "import keyword\n",
    "print(keyword.kwlist)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### condition\n",
    "\n",
    "A condition is a Boolean expression with the value True or False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n",
      "True\n",
      "False True False\n"
     ]
    }
   ],
   "source": [
    "print(2==3) #equality operator\n",
    "print(2!=3)\n",
    "print(2<=3)\n",
    "print(2<3 and 2<1, 2<3 or 2<1, not(2<3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Making Decisions with the if Statement\n",
    "\n",
    "There can be zero or more elif parts, and the else part is optional. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "#A statement ends with a colon means a block of code. The line below it blongs to this line.\n",
    "#Blocks of code are denoted by line indentation, which is rigidly enforced.\n",
    "#The line indentations should have the save style. For example, 4 spaces or a tab. Do not mix use of them!\n",
    "\n",
    "m = 2\n",
    "if m == 1:\n",
    "    print(1)\n",
    "elif m == 2:\n",
    "    print(2)\n",
    "else:\n",
    "    print(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.2 data structure\n",
    "\n",
    "### 2.2.1 list\n",
    "\n",
    "create"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5]\n",
      "[1, 'hello', 2.5, [1, 3, 5]]\n",
      "['w', 'o', 'r', 'l', 'd']\n",
      "[0, 1, 2, 3, 4]\n",
      "[2, 3, 4]\n",
      "[1, 3, 5, 7, 9]\n",
      "[10, 9, 8, 7, 6, 5, 4, 3, 2]\n"
     ]
    }
   ],
   "source": [
    "a=[1,2,3,4,5] #square brackets\n",
    "print(a)\n",
    "b=[1,'hello',2.5,[1,3,5]] #the data type in list can be different\n",
    "print(b)\n",
    "c=list('world') #key word 'list' can convert to list type\n",
    "print(c)\n",
    "\n",
    "#generate list by inner function 'range'\n",
    "print(list(range(5)))\n",
    "print(list(range(2,5)))\n",
    "print(list(range(1,10,2)))\n",
    "print(list(range(10,1,-1)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "use"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 5\n",
      "[1, 2, 3, 4, 100]\n"
     ]
    }
   ],
   "source": [
    "print(a[0],a[-1])\n",
    "a[4] = 100\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "slice"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 3]\n",
      "[2, 3, 4, 100]\n",
      "[1, 2, 3]\n",
      "[2, 3]\n",
      "[3, 4, 100]\n"
     ]
    }
   ],
   "source": [
    "print(a[1:3]) #[start, end)\n",
    "print(a[1:])\n",
    "print(a[:3])\n",
    "print(a[1:-2])\n",
    "print(a[-3:])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "100\n",
      "2500\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "print(len(a))\n",
    "print(max(a))\n",
    "print(sum(range(1,101,2)))\n",
    "e = [1,2,1,1,2]\n",
    "print(e.count(1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "add"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 100, 4]\n",
      "[1, 2, 3, 4, 100, 4, 'w', 'o', 'r', 'l', 'd']\n",
      "[1, 2, 0, 3, 4, 100, 4, 'w', 'o', 'r', 'l', 'd']\n"
     ]
    }
   ],
   "source": [
    "a.append(4) #add an element at the end\n",
    "print(a)\n",
    "a.extend(c) #add a list at the end\n",
    "print(a)\n",
    "a.insert(2,0) #add at given position\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "delete"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 100, 4, 'w', 'o', 'r', 'l', 'd']\n",
      "[1, 2, 3, 4, 100, 4, 'w', 'o', 'r', 'l']\n",
      "[1, 2, 3, 100, 4, 'w', 'o', 'r', 'l']\n",
      "[1, 2, 3, 100]\n"
     ]
    }
   ],
   "source": [
    "a.pop(2)\n",
    "print(a)\n",
    "x=a.pop()\n",
    "print(a)\n",
    "a.remove(4) #when there are more than one element of 4, only remove the first one\n",
    "print(a)\n",
    "del a[4:]\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "modify"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 100, 5, 6, 7]\n",
      "[5, 6, 7, 5, 6, 7, 5, 6, 7]\n",
      "[100, 3, 2, 1]\n",
      "[1, 2, 3, 100]\n",
      "[100, 3, 2, 1]\n"
     ]
    }
   ],
   "source": [
    "f=list(range(5,8))\n",
    "print(a+f) #merge\n",
    "print(f*3) #repeat\n",
    "a.reverse() #change a\n",
    "print(a)\n",
    "a.sort()\n",
    "print(a)\n",
    "print(list(reversed(a))) # not change"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "find"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n",
      "2\n",
      "False\n"
     ]
    },
    {
     "ename": "ValueError",
     "evalue": "'hello' is not in list",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-18-3fe64440517e>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0md\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'you'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'me'\u001b[0m \u001b[1;32min\u001b[0m \u001b[0md\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0md\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'hello'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m: 'hello' is not in list"
     ]
    }
   ],
   "source": [
    "print([1,2,2,2,2,3,3].count(2))\n",
    "d=['How','are','you']\n",
    "print(d.index('you'))\n",
    "print('me' in d)\n",
    "#print(d.index('hello'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2.2 tuple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1, 2, 3)\n",
      "(1, 2, 3, 4)\n",
      "(5,)\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "'tuple' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-17-e70a2b231867>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m5\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;36m4\u001b[0m \u001b[1;31m#can not modify!\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
     ]
    }
   ],
   "source": [
    "a=(1,2,3) #parenthesis\n",
    "print(a)\n",
    "print(tuple([1,2,3,4])) #key word 'tuple' change to tuple type\n",
    "b=5,\n",
    "print(b)\n",
    "a[1]=4 #can not modify!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2.3 dict\n",
    "\n",
    "build"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'math': 100, 'physics': 80, 'computer': 90}\n",
      "{'english': 60, 'art': 40}\n",
      "{'math': 100, 'physics': 100, 'computer': 100}\n"
     ]
    }
   ],
   "source": [
    "a={'math':100, 'physics': 80, 'computer':90} #braces\n",
    "print(a)\n",
    "items=[('english',60), ('art',40)]\n",
    "b=dict(items) #key word 'dict' change to dict type\n",
    "print(b)\n",
    "c=dict.fromkeys(['math','physics','computer'], 100) #these keys have the same value 100\n",
    "print(c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "add"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'math': 100, 'physics': 80, 'computer': 90, 'history': 85}\n"
     ]
    }
   ],
   "source": [
    "a['history']=85\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "delete"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'math': 100, 'physics': 80, 'computer': 90}\n"
     ]
    }
   ],
   "source": [
    "a.pop('history') #the key must exist, otherwise raise error. return the value to be deleted\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "modify"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'english': 60, 'art': 50}\n",
      "{'english': 60, 'art': 50, 'math': 100, 'physics': 80, 'computer': 90}\n"
     ]
    }
   ],
   "source": [
    "b['art'] = 50\n",
    "print(b)\n",
    "b.update(a)\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "find"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "None 0\n"
     ]
    }
   ],
   "source": [
    "print('math' in a)\n",
    "print(a.get('philosophy'), a.get('philosophy',0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "traverse"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['math', 'physics', 'computer']\n",
      "[100, 80, 90]\n",
      "[('math', 100), ('physics', 80), ('computer', 90)]\n"
     ]
    }
   ],
   "source": [
    "print(list(a.keys()))\n",
    "print(list(a.values()))\n",
    "print(list(a.items()))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "default dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n"
     ]
    },
    {
     "ename": "KeyError",
     "evalue": "'Chinese'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-25-8ff67d5d4766>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[0mdic\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mdefaultdict\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mint\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdic\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'a'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'Chinese'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mKeyError\u001b[0m: 'Chinese'"
     ]
    }
   ],
   "source": [
    "from collections import defaultdict\n",
    "dic = defaultdict(int)\n",
    "print(dic['a'])\n",
    "print(a['Chinese'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "ordered dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a A\n",
      "b B\n",
      "c C\n",
      "d D\n"
     ]
    }
   ],
   "source": [
    "from collections import OrderedDict\n",
    "d1 = OrderedDict()  #convert ordinary dict to ordered dict\n",
    "d1['a'] = 'A'\n",
    "d1['b'] = 'B'\n",
    "d1['c'] = 'C'\n",
    "d1['d'] = 'D'\n",
    "for k,v in d1.items():\n",
    "    print(k,v)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2.4 set\n",
    "\n",
    "defination"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'b', 'c', 'a'} {'b', 'd', 'c'} set()\n"
     ]
    }
   ],
   "source": [
    "x = set('abc')\n",
    "y = {'b','c','d'}\n",
    "z = set() #empty set can not use {} to define\n",
    "print(x,y,z)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{}\n",
      "<class 'dict'>\n"
     ]
    }
   ],
   "source": [
    "z2 = {}\n",
    "print(z2)\n",
    "print(type(z2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "operation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'b', 'c'}\n",
      "{'d', 'b', 'a', 'c'}\n",
      "{'a'}\n",
      "{'d', 'a'}\n"
     ]
    }
   ],
   "source": [
    "print(x&y)\n",
    "print(x|y)\n",
    "print(x-y)\n",
    "print(x^y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "print(len(x))\n",
    "print('a' in x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "modify"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'b', 'c'}\n",
      "{'b', 'c', 'e'}\n"
     ]
    }
   ],
   "source": [
    "x.remove('a')\n",
    "print(x)\n",
    "x.update('e')\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'e', 'b', 'f', 'c'}\n"
     ]
    }
   ],
   "source": [
    "x.add('f')\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "find"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "print(z.issubset(x))\n",
    "print(z<x)\n",
    "print(x.issuperset(z))\n",
    "print(x<y or x==y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "frozenset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "frozenset({1, 2, 3})\n"
     ]
    },
    {
     "ename": "AttributeError",
     "evalue": "'frozenset' object has no attribute 'add'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-37-702a58e86729>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0ms\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mfrozenset\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ms\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0ms\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0madd\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m: 'frozenset' object has no attribute 'add'"
     ]
    }
   ],
   "source": [
    "s = frozenset([1,2,3])\n",
    "print(s)\n",
    "s.add(4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2.5 enum"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import enum\n",
    "\n",
    "@enum.unique #can not repeat\n",
    "class Color(enum.Enum):\n",
    "    red = 0\n",
    "    green = 1\n",
    "    blue = 2\n",
    "    \n",
    "print(Color['red'], Color.red.name, Color.red.value, Color(1))\n",
    "for c in Color:\n",
    "    print(c)\n",
    "\n",
    "#can not compare\n",
    "print(Color.red < Color.blue)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.3 cyclic"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### while"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5050\n"
     ]
    }
   ],
   "source": [
    "sum = 0\n",
    "i=1\n",
    "while i <= 100: #indentation\n",
    "    sum += i\n",
    "    i += 1\n",
    "print(sum)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### for"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 1 4 9 16 25 36 49 64 81 \n",
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "for i in range(10):\n",
    "    print(i*i, end=' ')\n",
    "print()\n",
    "    \n",
    "a=[1,2,3,4,5]\n",
    "for i in a:\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "for dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(math,100)\n",
      "(physics,80)\n",
      "(computer,90)\n",
      "math 100\n",
      "physics 80\n",
      "computer 90\n"
     ]
    }
   ],
   "source": [
    "d={'math':100, 'physics': 80, 'computer':90}\n",
    "for k in d:\n",
    "    print('(%s,%d)' %(k,d[k]))\n",
    "\n",
    "for k,v in d.items():\n",
    "    print(k,v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello 1\n",
      "1.200000\n",
      "world\n",
      "8\n",
      "10\n"
     ]
    }
   ],
   "source": [
    "a=1\n",
    "print('hello %d'%a)\n",
    "b=1.2\n",
    "print('%f'%b)\n",
    "c='world'\n",
    "print('%s'%c)\n",
    "d=8\n",
    "print('%0x'%d)\n",
    "print('%0o'%d)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "special for"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "sai: 28\n",
      "wang: 26\n",
      "li: 24\n",
      "0 sai\n",
      "1 wang\n",
      "2 li\n"
     ]
    }
   ],
   "source": [
    "name = ['sai', 'wang', 'li']\n",
    "age = [28, 26, 24]\n",
    "for n,a in zip(name,age):\n",
    "    print('%s: %d' %(n,a))\n",
    "for i,v in enumerate(name):\n",
    "    print(i,v)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### break, continue and for...else"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "is a prime number\n"
     ]
    }
   ],
   "source": [
    "n=41\n",
    "for i in range(2,n//2):\n",
    "    if n%i == 0:\n",
    "        print('composite number')\n",
    "        break\n",
    "else: #for-else is very useful\n",
    "    print('is a prime number')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2500\n"
     ]
    }
   ],
   "source": [
    "sum = 0\n",
    "for i in range(1,100):\n",
    "    if i%2==0:\n",
    "        continue\n",
    "    sum += i\n",
    "print(sum)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'apple': 1, 'orange': 3, 'banana': 2}\n",
      "0\n",
      "defaultdict(<class 'int'>, {'apple': 1, 'orange': 3, 'banana': 2})\n"
     ]
    }
   ],
   "source": [
    "text = ['apple', 'orange', 'banana', 'orange', 'banana', 'orange']\n",
    "\n",
    "d = {}\n",
    "for fruit in text:\n",
    "    if fruit in d:\n",
    "        d[fruit] += 1\n",
    "    else:\n",
    "        d[fruit] = 1\n",
    "print(d)\n",
    "\n",
    "from collections import defaultdict\n",
    "d2 = defaultdict(int)\n",
    "for fruit in text:\n",
    "    d2[fruit] += 1\n",
    "print(d2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "*\n",
      "**\n",
      "***\n",
      "****\n",
      "*****\n"
     ]
    }
   ],
   "source": [
    "for i in range(5):\n",
    "    for j in range(i+1):\n",
    "        print('*',end='')\n",
    "    print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "         *\n",
      "        ***\n",
      "       *****\n",
      "      *******\n",
      "     *********\n",
      "    ***********\n",
      "   *************\n",
      "  ***************\n",
      " *****************\n",
      "*******************\n"
     ]
    }
   ],
   "source": [
    "n = 10\n",
    "for i in range(1,n+1):\n",
    "    for j in range(n-i):\n",
    "        print(' ',end='')\n",
    "    for j in range(2*i-1):\n",
    "        print('*',end='')\n",
    "    print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1*1=1  \n",
      "1*2=2  2*2=4  \n",
      "1*3=3  2*3=6  3*3=9  \n",
      "1*4=4  2*4=8  3*4=12 4*4=16 \n",
      "1*5=5  2*5=10 3*5=15 4*5=20 5*5=25 \n",
      "1*6=6  2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 \n",
      "1*7=7  2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 \n",
      "1*8=8  2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 \n",
      "1*9=9  2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81 \n"
     ]
    }
   ],
   "source": [
    "for i in range(1,10):\n",
    "    for j in range(1,i+1):\n",
    "        print('%d*%d=%-2d '%(j,i,i*j), end='')\n",
    "    print()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.4 function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "def is_even(n):\n",
    "    return n%2 == 0\n",
    "\n",
    "result = is_even(4)\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n"
     ]
    }
   ],
   "source": [
    "def gcd(m,n): #indentation\n",
    "    while n:\n",
    "        r = m%n\n",
    "        m = n\n",
    "        n = r\n",
    "    return m\n",
    "\n",
    "print(gcd(20,30))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "438\n"
     ]
    }
   ],
   "source": [
    "def digits2number(lst):\n",
    "    n = 0\n",
    "    for d in lst:\n",
    "        n = n*10 + d\n",
    "    return n\n",
    "\n",
    "print(digits2number([4,3,8]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5]\n"
     ]
    }
   ],
   "source": [
    "def number2digits(n):\n",
    "    lst = []\n",
    "    while n:\n",
    "        lst.append(n%10)\n",
    "        n //= 10\n",
    "    lst.reverse()\n",
    "    return lst\n",
    "\n",
    "print(number2digits(12345))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "default parameter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "30\n",
      "12\n",
      "6\n",
      "35\n"
     ]
    }
   ],
   "source": [
    "def area(width=2,height=3):\n",
    "    return width*height    \n",
    "\n",
    "print(area(5,6))\n",
    "print(area(4)) #do not give the second parameter, use the default value\n",
    "print(area())\n",
    "print(area(height=7,width=5)) #do not care about the parameters' order"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "return more than one value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def div(a, b):\n",
    "    return (a/b, a%b)\n",
    "print(div(7,3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "arbitrary number of parameters"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n",
      "10\n"
     ]
    }
   ],
   "source": [
    "def f(*arg):\n",
    "    sum_ = 0\n",
    "    for i in arg:\n",
    "        sum_ += i\n",
    "    return sum_\n",
    "\n",
    "print(f(1,2,3))\n",
    "print(f(1,2,3,4))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a : 1\n",
      "b : 2\n",
      "c : 3\n"
     ]
    }
   ],
   "source": [
    "def g(**arg):\n",
    "    for key in arg:\n",
    "        print(key,':',arg[key])  \n",
    "        \n",
    "g(a=1,b=2,c=3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "blank function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def h(a):\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "global paramter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    "parameter = 1\n",
    "def glb(parameter):\n",
    "    return parameter + globals()['parameter']\n",
    "print(glb(2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "nested function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "10\n"
     ]
    }
   ],
   "source": [
    "def multiplier(factor):\n",
    "    def multiplyByFactor(number):\n",
    "        return number*factor\n",
    "    return multiplyByFactor\n",
    "\n",
    "double = multiplier(2)\n",
    "print(double(5))\n",
    "print(multiplier(2)(5))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "lambda function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, -2, 3, -4]\n"
     ]
    }
   ],
   "source": [
    "h = [3,-2, 1,-4]\n",
    "h.sort(key=lambda x:abs(x)) #lambda input : output\n",
    "print(h)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.5 string\n",
    "\n",
    "### 2.5.1 transform"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "123\n",
      "123 1.23\n",
      "a= 456\n",
      "a= 456\n"
     ]
    }
   ],
   "source": [
    "print(str(123)) \n",
    "print(int('123'),float('1.23'))\n",
    "a=456\n",
    "print('a=',repr(a))\n",
    "print('a=',repr(a))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.5.2 modify"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "abcabcabcabc\n",
      "abcdef\n",
      "abc def\n",
      "How are you\n",
      "how 1r5 you\n",
      "my name is John\n",
      "my name is John\n"
     ]
    }
   ],
   "source": [
    "print('abc' * 4)\n",
    "print('abc' + 'def')\n",
    "\n",
    "print(' \\tabc def  '.strip()) #delete blanks at the two ends\n",
    "\n",
    "s = 'how are you'\n",
    "print(s.replace('how', 'How'))\n",
    "\n",
    "table = str.maketrans('abcde' , '12345') #len(table)=256\n",
    "print(s.translate(table))\n",
    "\n",
    "import string\n",
    "#after $ is what to be replaced\n",
    "template = string.Template('my name is $name')\n",
    "print(template.substitute(name='John'))\n",
    "d = {'name': 'John'}\n",
    "print(template.substitute(d))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.5.3 find"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n",
      "-1\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "print(s.find('are'))\n",
    "print(s.find('123'))\n",
    "print(s.find('are', 2, 8)) #give the start and end points"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.5.4 function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "how are you\n",
      "2\n",
      "How Are You\n",
      "HOW ARE YOU\n",
      "False False True True\n"
     ]
    }
   ],
   "source": [
    "print(s)\n",
    "print(s.count('o'))\n",
    "\n",
    "print(s.title())\n",
    "print(s.upper())\n",
    "\n",
    "print(' 123'.isdigit(),'4.56'.isdigit(), 'abc'.isalpha(), 'a2'.isalnum())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.5.5 split and join"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['how', 'are', 'you']\n",
      "how are you\n"
     ]
    }
   ],
   "source": [
    "l = s.split(' ') #default separator is blank character\n",
    "\n",
    "print(l)\n",
    "print(' '.join(l)) #join a list to a string"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.5.6 format"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a=4, b=5.68\n",
      "a=4  , b= 5.68\n",
      "how a\n"
     ]
    }
   ],
   "source": [
    "a=4\n",
    "b=5.678\n",
    "print('a=%d, b=%.2f' %(a,b))\n",
    "print('a=%-3d, b=%5.2f' %(a,b))\n",
    "\n",
    "print('%.*s' % (5,s))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a= 1.23\n",
      "world hello world\n",
      "math：90, computer 80\n",
      "value of class is：5\n",
      "#123, 20 ,-3.14\n"
     ]
    }
   ],
   "source": [
    "print('{} {}'.format('a=',1.23))\n",
    "print('{1} {0} {1}'.format('hello', 'world'))\n",
    "\n",
    "score = {'math':90, 'computer':80}\n",
    "print('math：{math}, computer {computer}'.format(**score))\n",
    "\n",
    "class C:\n",
    "    def __init__(self,v):\n",
    "        self.v = v\n",
    "\n",
    "n = C(5)\n",
    "print('value of class is：{0.v}'.format(n))\n",
    "#> means right allign，# is padding character，^ is middle allign\n",
    "print('{:#>4d},{:^4o},{:+.2f}'.format(123,16,-3.14159))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.5.7 bytes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b''\n",
      "b'\\x00\\x00\\x00\\x00\\x00'\n",
      "<class 'bytes'>\n",
      "b'\\xb0\\xa1'\n",
      "b'abcABC01'\n"
     ]
    }
   ],
   "source": [
    "print(bytes())\n",
    "a = bytes(5)\n",
    "print(a)\n",
    "print(type(a))\n",
    "print(b'\\xb0\\xa1')\n",
    "\n",
    "#ASCII code\n",
    "b = bytes([97,98,99, 65,66,67, 48,49])\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "bytearray(b'ac')\n"
     ]
    }
   ],
   "source": [
    "d = bytearray([97,98,99]) #changeable\n",
    "del d[1]\n",
    "print(d)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'\\xe8\\xb5\\x9b\\xe7\\x90\\xb3\\xe4\\xbc\\x9f'\n"
     ]
    }
   ],
   "source": [
    "e = '赛琳伟'\n",
    "print(bytes(e, encoding='utf-8'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.6 file\n",
    "\n",
    "### 2.6.1 write"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('test.txt','w')\n",
    "f.write('hello ')\n",
    "f.write('world')\n",
    "f.write('123\\n')\n",
    "f.write('\\\\456')\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "open mode:\n",
    "\n",
    "r: Reading only. This is the default mode.\n",
    "\n",
    "rb: Opens a file for reading only in binary format\n",
    "\n",
    "r+: Opens a file for both reading and writing\n",
    "\n",
    "rb+: Opens a file for both reading and writing in binary format\n",
    "\n",
    "w: Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing\n",
    "\n",
    "a: Opens a file for appending. The file pointer is at the end of the file if the file exists. If the file does not exist, it creates a new file for writing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "additional"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "f = open('test.txt','a')\n",
    "f.write('\\n'+str(123))\n",
    "f.write('\\n456')\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.6.2 read"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello\n",
      " world123\n",
      " "
     ]
    }
   ],
   "source": [
    "g=open('test.txt','r') #encoding='utf-8'\n",
    "a=g.read(5)\n",
    "print(a)\n",
    "print(g.readline(), end=' ')\n",
    "#print g.readlines()\n",
    "g.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.6.3 binary file\n",
    "\n",
    "write"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "import struct\n",
    "\n",
    "fb = open('test.bin','wb')\n",
    "fb.write(struct.pack('f',3.14))\n",
    "fb.write(struct.pack('i',5))\n",
    "fb.write(struct.pack('i',6))\n",
    "fb.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "read"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(3.140000104904175,)\n",
      "(5, 6)\n"
     ]
    }
   ],
   "source": [
    "gb = open('test.bin','rb')\n",
    "print(struct.unpack('f', gb.read(4)))\n",
    "print(struct.unpack('2i', gb.read(8)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.6.4 random read & write"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "30\n"
     ]
    }
   ],
   "source": [
    "f = open('test.txt','r+')\n",
    "\n",
    "#parameter 1: offset\n",
    "#parameter 2: relative position. 0 is head, 1 is current, 2 is tail\n",
    "#It only can calculate relative position from the head if not open with mode 'b'\n",
    "f.seek(0,2) # go to the 2th byte in the file\n",
    "print(f.tell())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.7 list comprehension\n",
    "### 2.7.1 list comprehension"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 2, 4, 6, 8]\n",
      "[(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]\n"
     ]
    }
   ],
   "source": [
    "a=[x*2 for x in range(5)]\n",
    "print(a)\n",
    "\n",
    "print([(x,y) for x in [1,2,3] for y in [4,5]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.7.2 map"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 1, 4, 9, 16]\n",
      "[0, 1, 4, 9, 16]\n"
     ]
    }
   ],
   "source": [
    "def square(n):\n",
    "    return n*n\n",
    "\n",
    "c = list(map(square, list(range(5))))\n",
    "print(c)\n",
    "\n",
    "d = list(map(lambda x:x*x, list(range(5))))\n",
    "print(d)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.7.3 filter"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 2, 4, 6, 8]\n"
     ]
    }
   ],
   "source": [
    "def isEven(n):\n",
    "    return not n%2\n",
    "\n",
    "print(list(filter(isEven, list(range(10)))))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.7.4 reduce"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5050\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'\\n[0,1,2,3,...]\\n[1,2,3,...]\\n[3,3,...]\\n[6,...]'"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from functools import reduce\n",
    "\n",
    "print(reduce(lambda x,y: x+y, list(range(101))))\n",
    "\n",
    "\"\"\"\n",
    "[0,1,2,3,...]\n",
    "[1,2,3,...]\n",
    "[3,3,...]\n",
    "[6,...]\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.8 module\n",
    "\n",
    "### 2.8.1 import"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.141592653589793\n",
      "1.4142135623730951\n",
      "2.718281828459045\n",
      "1.4142135623730951\n"
     ]
    }
   ],
   "source": [
    "import math\n",
    "print(math.pi)\n",
    "\n",
    "from math import sqrt\n",
    "print(sqrt(2))\n",
    "\n",
    "from math import * #import all\n",
    "print(e)\n",
    "\n",
    "from math import sqrt as kaifang\n",
    "print(kaifang(2))\n",
    "\n",
    "#import custom module\n",
    "import sys\n",
    "sys.path.append('C:/mypath')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.8.2 os module"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "D:\\360disk\\教学\\scientific computing and data processing with python\n",
      "D:\\360disk\\教学\\scientific computing and data processing with python\\test.txt\n",
      "D:\\360disk\\教学\\scientific computing and data processing with python test.txt\n",
      "('test', '.txt')\n",
      "['.ipynb_checkpoints', '123.txt', '2022名单.xls', '2023名单.xls', 'a.npy', 'ani.py', 'c.bin', 'chapter_1.html', 'chapter_1.ipynb', 'chapter_10 - 副本.ipynb', 'chapter_10.ipynb', 'chapter_2 - 副本.ipynb', 'chapter_2.ipynb', 'chapter_3.ipynb', 'chapter_4.ipynb', 'chapter_5.ipynb', 'chapter_6.ipynb', 'chapter_7.ipynb', 'chapter_8.ipynb', 'chapter_9.ipynb', 'csv_dict_test.csv', 'csv_test.csv', 'data.h5', 'data.json', 'fig', 'final exam 2022.docx', 'homework', 'homework.docx', 'homework.ipynb', 'homework8.3.csv', 'NG-CO2.csv', 'pandas_csv.csv', 'pandas_excel.xls', 'pandas_excel.xlsx', 'python', 'test.bin', 'test.txt', '__pycache__', '劳动生产率.xlsx', '旋轮线.gif', '班级成绩单(8).doc', '研1-3 Python简介.pptx', '进度安排.xlsx']\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "print(os.path.exists('test.txt'))\n",
    "path = os.getcwd() #current path\n",
    "print(path)\n",
    "total_name = os.path.join(path, 'test.txt')\n",
    "print(total_name)\n",
    "folder_name, file_name = os.path.split(total_name)\n",
    "print(folder_name, file_name)\n",
    "print(os.path.splitext(file_name))\n",
    "print(os.listdir())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.8.3 random module"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.0869782639043718\n",
      "10\n",
      "11\n",
      "129.0377045075799\n",
      "0\n",
      "9\n",
      "[3, 7, 2, 4, 9, 5]\n",
      "[6, 3, 0, 5, 4, 1, 8, 2, 7, 9]\n",
      "1.3516997825874104\n"
     ]
    }
   ],
   "source": [
    "from random import *\n",
    "\n",
    "print(random()) #a random real number in [0,1)\n",
    "print(randint(5,10)) #a random integer in [5,10]\n",
    "print(getrandbits(4)) #random n bits\n",
    "print(uniform(100, 200)) #返random real number in [100,200)\n",
    "print(randrange(0,10,2)) #([start], stop, [step])\n",
    "print(choice(range(10))) #random select\n",
    "print(sample(range(10), 6)) #sample from a list\n",
    "s = list(range(10))\n",
    "shuffle(s)\n",
    "print(s)\n",
    "print(gauss(0,1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.8.4 time module"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1695643835.6764393\n",
      "Mon Sep 25 20:10:35 2023\n",
      "I sleep 3 seconds.\n"
     ]
    }
   ],
   "source": [
    "from time import *\n",
    "\n",
    "t = time() #1970-1-1\n",
    "print(t)\n",
    "s = ctime(t) #number to string\n",
    "print(s)\n",
    "sleep(3)\n",
    "print('I sleep 3 seconds.')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.8.5 itertools module"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('a', '1'), ('a', '2'), ('a', '3'), ('b', '1'), ('b', '2'), ('b', '3')]\n",
      "[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]\n",
      "[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]\n",
      "[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]\n",
      "[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'B'), ('B', 'C'), ('C', 'C')]\n"
     ]
    }
   ],
   "source": [
    "import itertools\n",
    "\n",
    "print(list(itertools.product('ab', '123')))\n",
    "print(list(itertools.permutations(range(1,4))))\n",
    "print(list(itertools.permutations(range(1,4), 2)))\n",
    "print(list(itertools.combinations(range(1,5), 3)))\n",
    "print(list(itertools.combinations_with_replacement('ABC', 2)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.9 exception"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "an exception occur\n",
      "execute whenever an exception occur or not\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    1/0\n",
    "except:\n",
    "    print('an exception occur')\n",
    "else:\n",
    "    print('no exception')\n",
    "finally:\n",
    "    print('execute whenever an exception occur or not')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "raise 'something error'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "break loop"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 9\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    for i in range(5):\n",
    "        for j in range(10):\n",
    "            if i+j>8:\n",
    "                raise\n",
    "except:\n",
    "    print(i,j)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.10 Object-Oriented Programming\n",
    "\n",
    "A class encapsulate data and the functions that operate on them.\n",
    "\n",
    "Object-oriented programming makes it easier for you to design, implement, test and update applications.\n",
    "\n",
    "Classes are new data types."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Student:\n",
    "    count = 0 #student number\n",
    "    \n",
    "    def __init__(self, name, age):\n",
    "        '''construct fucntion'''\n",
    "        self.name = name\n",
    "        self.__age = age #private property starts with __\n",
    "        Student.count += 1\n",
    "        \n",
    "    def __del__(self):\n",
    "        '''destruct function\n",
    "        '''\n",
    "        Student.count -= 1\n",
    "        \n",
    "    def set_score(self, math, physics, computer):\n",
    "        self.score = [math,physics,computer]\n",
    "        \n",
    "    def score_sum(self):\n",
    "        return sum(self.score)\n",
    "    \n",
    "    def get_age(self):\n",
    "        return self.__age"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s1 = Student('Wang', 20) #define an object\n",
    "print(s1.name)\n",
    "s1.set_score(80,90,100)\n",
    "print(s1.score_sum())\n",
    "print(Student.count)\n",
    "print(s1.get_age())\n",
    "print(s1.__age)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Inheritance\n",
    "\n",
    "When creating a new class, instead of writing all new code, you can designate that the new class is to be formed initially by inheriting the attributes and methods of a previously defined base class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Graduate(Student): #Inherit from Student class\n",
    "    def __init__(self, name, age, tutor):\n",
    "        super(Graduate, self).__init__(name, age)\n",
    "        self.tutor = tutor\n",
    "        \n",
    "    def set_score(self, math, physics, computer, python):\n",
    "        self.score = [math,physics,computer,python]\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sai\n",
      "True\n",
      "(<class '__main__.Student'>,)\n",
      "<class '__main__.Graduate'>\n",
      "True True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "s2 = Graduate('Li', 25, 'Sai')\n",
    "print(s2.tutor)\n",
    "\n",
    "print(issubclass(Graduate, Student))\n",
    "print(Graduate.__bases__) #see the base classes\n",
    "print(s2.__class__) #belong to which class\n",
    "print(isinstance(s2, Graduate), isinstance(s2, Student))\n",
    "print(hasattr(s2, 'tutor'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Polymorphism\n",
    "\n",
    "You may simply send the same method call to objects possibly of many different types. Each object responds by doing the right thing."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "s2.set_score(70,80,90,100)\n",
    "print(s2.score_sum())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Homework\n",
    "1. Create a string variable \"Orange's unit price is 5 yuan.\" Extract the number 5 inside and assign it to the new variable. Check the data type of the new variable, convert the extracted number 5 to an integer (int), and confirm whether the data type conversion was successful.\n",
    "2. Find the sum of numbers less than n that can be divisible by 3 or 5\n",
    "3. Fibonacci sequence, also known as the golden section sequence, was introduced by mathematician Leonardo Fibonacci as an example of rabbit reproduction, hence the term \"rabbit sequence\". It refers to a sequence of numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34. In mathematics, Fibonacci sequence is defined recursively as follows.\n",
    "\n",
    "$F(1) = 1$\n",
    "\n",
    "$F(2) = 1$\n",
    "\n",
    "$F(n) = F(n-1)+F(n-2)(n\\geq3,n\\in\\mathbb{N^+})$\n",
    "\n",
    "Requirement 1: Output the 10th Fibonacci sequence.\n",
    "\n",
    "Requirement 2: Output a specified number of Fibonacci sequences."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
